<template>
	<!-- 修改时，需要处理 处理人 的回显，主要为弹窗的赋值 -->
	<view class="page">
		<view class="name2">
			<text class="name2_1">{{info.sname}} {{info.dir}}</text>
		</view>
		<scroll-view scroll-y="true" class="scroll-Y">
			<uni-forms ref="valiForm" :modelValue="formData" label-width="160rpx" :rules="rules">
				<uni-forms-item label="故障现象" name="xianxiang" required>
					<uni-easyinput type="text" v-model="formData.xianxiang" placeholder="请输入故障现象" :disabled="tchange" />
				</uni-forms-item>
				<uni-forms-item label="提交人" name="people1">
					<!-- <view @click="control1 = true">
						<uni-easyinput placeholder="请选择提交人" v-model="people1" disabled />
					</view>
					<z-multi-choose activeColor="red" idKey="realname" showKey="realname" :list="users" :show="control1"
						@maskTouch="cancle_p1" @sure="comform_p1" @cancle="cancle_p1"></z-multi-choose> -->
					<!-- <uni-easyinput type="text" v-model="formData.people" placeholder="请输入处理人" /> -->
					<!-- <view class="form">
						<view class="item">
							<view :class="['select', form.selectValue ? 'selected' : '']"
								@tap="handleMultiple(form.selectIndex)">
								{{form.selectValue || '请选择'}}
							</view>
						</view>
					</view> -->
					<!-- <uni-easyinput placeholder="请选择提交人" @tap="handleMultiple(tPeople.value)" v-model="tPeople.show"
						disabled /> -->
					<text @tap="handleMultiple(tPeople.value)">{{tPeople.show}}</text>
					<multiple-picker title="请选择" :show="selectMultiple.show" :columns="selectMultiple.columns"
						:defaultIndex="selectMultiple.index" @confirm="confirmMultiple"
						@cancel="selectMultiple.show = false" @change="changeMultiple"></multiple-picker>
				</uni-forms-item>
				<uni-forms-item label="故障类型Ⅰ" name="type" required>
					<uni-data-select v-model="formData.type" :localdata="fault_list"
						@change="fault_types2"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="故障类型Ⅱ" name="type" required>
					<uni-data-select v-model="formData.type2" :localdata="fault_list2"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="故障原因" name="yuanyin" required>
					<uni-easyinput type="textarea" maxlength="200" v-model="formData.yuanyin"
						placeholder="请输入故障原因(200字内)"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="处理措施" name="cuoshi" required>
					<uni-easyinput type="textarea" maxlength="200" v-model="formData.cuoshi"
						placeholder="请输入处理措施(200字内)未处理请不要填写此栏，处理措施将作为故障是否处理的评判标准"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="处理人" name="name">
					<!-- <uni-easyinput type="text" v-model="formData.people" placeholder="请输入处理人" /> -->
					<!-- <uni-easyinput placeholder="请选择处理人" @tap.stop.proevent="handleMultiple2(cPeople.value)" v-model="cPeople.show" @click="handleMultiple2(cPeople.value)"
					disabled /> -->
					<!-- <u--input placeholder="请选择处理人" @tap="handleMultiple2(cPeople.value)" v-model="cPeople.show" disabled></u--input> -->
					<!-- <div style="display: flex;align-items: center;"> -->
					<text @tap="handleMultiple2(cPeople.value)">{{cPeople.show}}</text>
					<!-- </div> -->
					<multiple-picker title="请选择" :show="selectMultiple2.show" :columns="selectMultiple2.columns"
						:defaultIndex="selectMultiple2.index" @confirm="confirmMultiple2"
						@cancel="selectMultiple2.show = false" @change="changeMultiple2"></multiple-picker>
				</uni-forms-item>
				<uni-forms-item label="备注" name="beizhu">
					<uni-easyinput type="textarea" maxlength="200" v-model="formData.beizhu"
						placeholder="请输入备注(200字内)"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="维修照片" name="pics1" label-width="240rpx">
					<view class="u-demo-block__content">
						<view class="u-page__upload-item">
							<u-upload :fileList="pics1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
								:maxCount="9"></u-upload>
						</view>
					</view>
				</uni-forms-item>
			</uni-forms>
		</scroll-view>
		<!-- <button @click="submit" class="btn">提交</button> v-show="toAdd" -->
		<u-button class="btn" @click="submit" type="primary" text="提交" />
	</view>
</template>

<script>
	import zMultiChoose from '@/components/z-multi-choose/z-multi-choose.vue'
	import MultiplePicker from '@/components/multiple-picker/multiple-picker.vue'
	import {
		getTreeJsonByCode
	} from '@/api/common.js';
	import {
		getTreeJsonChilds
	} from '@/api/common.js';
	import {
		baseURL
	} from '@/api/env.js'
	import {
		addAppMaintenance
	} from '@/api/common.js';
	import {
		getAppMaintenanceById
	} from '@/api/common.js';
	import {
		getAppTaskById
	} from '@/api/common.js';
	import {
		updateAppMaintenance
	} from '@/api/common.js';
	import {
		findSysUserAll
	} from '@/api/common.js';
	import {
		user_info
	} from '@/api/common.js';
	export default {
		components: {
			zMultiChoose,
			MultiplePicker
		},
		data() {
			return {
				tchange: false, //允许提报信息修改
				tPeople: {
					value: [],
					show: ''
				},
				cPeople: {
					value: [],
					show: ''
				},
				selectMultiple: {
					show: false, //是否弹出
					index: [],
					columns: [],
				},
				selectMultiple2: {
					show: false, //是否弹出
					index: [],
					columns: [],
				},
				info: '',
				formData: {
					cuoshi: '',
					peoples: '',
					submitDate: Date.now()
				},
				date_now: Date.now(),
				toAdd: true,
				id: '',
				pics1: [], //用于图片回显
				img1: [], //上传时数据处理
				autoUpload: false,
				rules: {
					type: {
						// rules: [{
						// 	required: true,
						// 	errorMessage: '此项不能为空',
						// }],
					},
					cuoshi: {
						// rules: [{
						// 	required: true,
						// 	errorMessage: '此项不能为空',
						// }],
					},
					yuanyin: {
						// rules: [{
						// 	required: true,
						// 	errorMessage: '此项不能为空',
						// }],
					}
				},
				fault_list: [],
				fault_list2: [],
				op: 0,
				taskid: '',
			}
		},
		onLoad(option) {
			if (option.data != undefined) {
				this.tchange = true
				console.log('传过来的data:' + option.data)
				var task = JSON.parse(option.data)
				this.formData.danhao = task.danhao
				this.formData.id = task.id
				this.formData.siteid = task.siteid
				this.formData.laiyuan = task.laiyuan
				this.formData.xianxiang = task.xianxiang
				console.log("task.maintenanceUser:" + task.maintenanceUser)
				if (task.maintenanceUser != undefined) {
					if (task.maintenanceUser.length > 0) {
						var people = task.maintenanceUser[0].people
						this.cPeople = {
							value: people.split(','),
							show: people
						}
					}
				}
				if (task.submitby != undefined) {
					this.tPeople = {
						value: task.submitby.split(','),
						show: task.submitby
					}
				}
				// this.fault_types2(this.formData.type)
			}
			if (option.op != undefined) {
				this.op = option.op
			}
			if (option.id != undefined) {
				this.tchange = true
				console.log('id:' + option.id)
				this.id = option.id
				//查詢一個详情
				this.detail()
				this.toAdd = false
			}
			if (option.taskid != undefined) {
				this.tchange = true
				console.log('taskid:' + option.taskid)
				this.taskid = option.taskid
				//查詢一個详情
				this.taskdetail()
			}
			if (option.info != undefined) {
				this.info = JSON.parse(option.info)
				this.formData.siteid = this.info.id
			}
			if (option.xianxiang != undefined) {
				this.formData.xianxiang = option.xianxiang
			}
			if (option.submitby != undefined) {
				this.tPeople = {
					value: option.submitby.split(','),
					show: option.submitby
				}
			}
			this.getUserInfo();
			this.fault_types();
			this.findSysUserAll();
		},
		methods: {
			handleMultiple(val) {
				console.log('handleMultiple:' + this.tchange);
				if (!this.tchange) {
					this.selectMultiple.index = val || [];
					this.selectMultiple.show = true;
				}
			},
			confirmMultiple(e) {
				console.log('confirmMultiple');
				console.log(e);

				let temp = [];
				e.selected.forEach(item => {
					temp.push(item.label);
				})
				this.tPeople.show = temp.toString();
				this.tPeople.value = e.value;
				this.selectMultiple.show = false;
			},
			changeMultiple(e) {
				console.log(e);
			},
			handleMultiple2(val) {
				console.log('handleMultiple2');
				console.log(val);

				this.selectMultiple2.index = val || [];
				this.selectMultiple2.show = true;
			},
			confirmMultiple2(e) {
				console.log('confirmMultiple2');
				console.log(e);

				let temp = [];
				e.selected.forEach(item => {
					temp.push(item.label);
				})
				this.cPeople.show = temp.toString();
				this.cPeople.value = e.value;
				this.selectMultiple2.show = false;
			},
			changeMultiple2(e) {
				console.log(e);
			},
			// getUserInfo() {
			// 	uni.getStorage({
			// 		key: 'UserInfo',
			// 		success: (e) => {
			// 			console.log('读取结果：' + JSON.stringify(e))
			// 			// this.loginForm.account = e.data.account
			// 			// this.loginForm.password = e.data.password
			// 		}
			// 	})
			// },
			getUserInfo() {
				user_info().then(res => {
					console.log('获取结果：' + JSON.stringify(res))
					if (this.op < 2 && this.tPeople.show.length == 0) {
						this.tPeople = {
							value: [res.userName],
							show: res.userName
						}
					}
					if (this.op < 3 && this.cPeople.show.length == 0) {
						this.cPeople = {
							value: [res.userName],
							show: res.userName
						}
					}
				}).catch(err => {
					console.log(err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
			},
			//获取人员
			findSysUserAll() {
				findSysUserAll().then(res => {
					console.log(res);
					this.selectMultiple.columns = []
					this.selectMultiple2.columns = []
					res.forEach(item => {
						//forEach循环
						this.selectMultiple.columns.push({
							label: item.realname,
							value: item.realname
						})
						this.selectMultiple2.columns.push({
							label: item.realname,
							value: item.realname
						})
					});
					console.log('更新用户列表')
					console.log(this.selectMultiple)

				}).catch(err => {
					console.log(err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
			},
			//获取故障类型
			fault_types() {
				getTreeJsonByCode({
					code: "FaultType"
				}).then(res => {
					console.log(res);
					if (res.length > 0) {
						this.fault_list = []
						res.forEach(item => {
							//forEach循环
							this.fault_list.push({
								value: item.id,
								text: item.value
							})
						});
					}
				}).catch(err => {
					console.log(err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
			},
			//获取故障类型2
			fault_types2(e) {
				console.log('准备获取故障类型2：' + e)
				console.log('准备获取故障类型2--：' + this.formData.type)
				getTreeJsonChilds({
					parentId: e
				}).then(res => {
					console.log(res);
					if (res.length > 0) {
						this.fault_list2 = []
						res.forEach(item => {
							//forEach循环
							this.fault_list2.push({
								value: item.id,
								text: item.value
							})
						});
					}
				}).catch(err => {
					console.log(err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
			},


			// 删除图片
			deletePic(event) {
				this[`pics${event.name}`].splice(event.index, 1)
				this[`img${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				console.log(event)
				let lists = [].concat(event.file)
				let fileListLen = this[`pics${event.name}`].length
				lists.map((item) => {
					this[`pics${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
					this[`img${event.name}`].push('')
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					console.log('上传结果：' + result)
					let item = this[`pics${event.name}`][fileListLen]
					this[`pics${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					this[`img${event.name}`].splice(fileListLen, 1, result)
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					var token = "";
					try {
						token = uni.getStorageSync('token')
					} catch (e) {}
					let a = uni.uploadFile({
						url: baseURL + '/file/ubatchUpload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'image',
						header: {
							Authorization: token
						},
						success: (res) => {
							var res1 = JSON.parse(res.data)
							console.log('结果：' + res.data)
							if (res1.flag) { //成功
								resolve(res1.data.id)
							}
						}
					});
				})
			},
			submit() {
				console.log('表单验证...')
				this.$refs['valiForm'].validate().then(res => {
					console.log('success', res);
					// console.log(JSON.stringify(this.formData.pics1)+'------'+this.pics1)
					this.formData.pic1 = JSON.stringify(this.img1)
					// this.formData.peoples = JSON.stringify(this.peopleArray)
					this.formData.peoples = this.cPeople.value
					this.formData.peoples1 = this.tPeople.value
					// if (this.id != undefined && this.id.length > 0) {
					// 	this.edit();
					// } else {
					this.add();
					// }
				}).catch(err => {
					console.log('err', err);
				})
			},
			edit() {
				addAppMaintenance(
					// updateAppMaintenance(
					this.formData).then(res => {
					console.log('查詢結果：' + JSON.stringify(res));
					uni.showToast({
						title: "修改成功",
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 500)
				}).catch(err => {
					console.log(err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
			},
			add() {
				addAppMaintenance(
					this.formData).then(res => {
					console.log('查詢結果：' + JSON.stringify(res));
					uni.showToast({
						title: "新增成功",
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 500)
				}).catch(err => {
					console.log(err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
			},
			detail() {
				getAppMaintenanceById(this.id).then(res => {
					console.log('查詢結果：' + JSON.stringify(res));
					this.formData = res
					var p1 = JSON.parse(this.formData.pic1)
					this.pics1 = []
					p1.forEach(item => {
						this.pics1.push({
							status: 'success',
							message: '',
							url: baseURL + '/file/img/' + item
						})
						this.img1.push(item)
					});
					console.log(this.formData.pics1)

					this.fault_types2(this.formData.type)
					// this.tPeople = {
					// 	value: this.formData.submitBy,
					// 	show: JSON.stringify(this.formData.submitBy)
					// }
					// this.cPeople = {
					// 	value: this.formData.people,
					// 	show: JSON.stringify(this.formData.people)
					// }

					this.tPeople = {
						value: this.formData.submitBy.split(','),
						show: this.formData.submitBy
					}
					this.cPeople = {
						value: this.formData.people.split(','),
						show: this.formData.people
					}

				}).catch(err => {
					console.log(err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
			},

			taskdetail() {
				getAppTaskById(this.taskid).then(res => {
					console.log('查詢結果：' + JSON.stringify(res));
					console.log('第一条记录匹配：' + res.maintenance)
					if (res.maintenance != undefined) {
						console.log('第一条记录匹配结果：' + JSON.stringify(res.maintenance))
						this.formData = res.maintenance
						console.log('第一条记录匹配后结果：' + JSON.stringify(this.formData))
						if (this.formData.pic1 != undefined) {
							var p1 = JSON.parse(this.formData.pic1)
							this.pics1 = []
							p1.forEach(item => {
								this.pics1.push({
									status: 'success',
									message: '',
									url: baseURL + '/file/img/' + item
								})
								this.img1.push(item)
							});
							console.log(this.formData.pics1)
						}

						this.fault_types2(this.formData.type)
						this.cPeople = {
							value: this.formData.people.split(','),
							show: this.formData.people
						}
					}
					this.formData.xianxiang = res.xianxiang
					this.tPeople = {
						value: res.submitBy.split(','),
						show: res.submitBy
					}

				}).catch(err => {
					console.log(err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		margin-top: 32rpx;
		width: 710rpx;
		margin-left: 16rpx;
		margin-right: 16rpx;
	}

	.scroll-Y {
		height: 82vh;
	}

	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}

	.name2 {
		height: 60rpx;
		width: 84vw;
		@include flex();
		margin-bottom: 2vh;

		.name2_1 {
			color: $font-color;
			font-size: 40rpx;
			width: 100vw;
			text-align: center;
		}
	}

	/* .btn{
		background-color: $bg-color;
	} */
</style>